<?php

class SinaUtil {

    /**
     * 根据图片路径上传新浪图床
     * @param string $picPath
     * @param string $cookie
     * @return string
     */
    public static function upload($picPath, $cookie) {
        $post_data['pic1'] = new CURLFile($picPath);
        $url = "https://picupload.weibo.com/interface/pic_upload.php?data=pic1&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog&cb=http://weibo.com/aj/static/upimgback.html?_wv=5&callback=STK_ijax_" . time() . rand(1000, 9999);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //multipart 方式上传需要注意传递的参数是数组，不是字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        preg_match('/\"pid\":\"(.*?)\"/', $output, $matches);
        if (isset($matches[1])) {
            unlink($picPath);
            return $matches[1];
        } else {
            return '/res/images/nav/' . basename($picPath);
        }
    }

    public static function uploadByBase64($picUrl, $cookie) {
        $ch = curl_init('https://picupload.weibo.com/interface/pic_upload.php?mime=image%2Fpng&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog');

        $file = @file_get_contents($picUrl);
        if (empty($file)) {
            return "";
        }

        $base64_file = base64_encode($file);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_VERBOSE => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => ["Cookie: $cookie"],
            CURLOPT_POSTFIELDS => ['b64_data' => $base64_file]
        ]);

        $res = curl_exec($ch);
        curl_close($ch);

        preg_match('/\"pid\":\"(.*?)\"/', $res, $matches);
        if (isset($matches[1])) {
            return $matches[1];
        } else {
            return "";
        }
    }

    /**
     * 根据图片链接上传新浪图床
     * @param string $picUrl
     * @param string $cookie
     * @return string
     */
    public static function uploadByUrl($picUrl, $cookie) {
        $path = '/usr/share/nginx/html/nav.dreamthere.com/res/images/nav/';
        if (ENVIRONMENT == 'development') {
            $path = APPPATH . '../res/images/nav/';
        }

        $filePath = $path . uniqid();
        if (!file_exists($path)) {
            mkdir($path);
            chmod($path, 755);
        }

        $file = @file_get_contents($picUrl);
        if (empty($file)) {
            return "";
        }

        file_put_contents($filePath, $file);
        if (file_exists($filePath)) {
            return self::upload($filePath, $cookie);
        } else {
            return "";
        }
    }

    /**
     * 获取新浪图床图片地址
     * @param string $pid         图片id
     * @param string $type        默认 large 枚举 square,thumb150,orj360,orj480,mw690,mw1024,mw2048,small,bmiddle,larg
     * @return string
     */
    public static function getImageUrl($pid, $type = 'large') {
        if (empty($pid)) {
            return "";
        }

        if (preg_match('/\/res.*/', $pid)) {
            $path = 'http://nav.dreamthere.com';
            if (ENVIRONMENT == 'development') {
                $path = 'http://localhost:8000';
            }
            return $path . $pid;
        }

        $pid_zone = crc32($pid);
        $zone = ($pid_zone & 3) + 1;
        $url = 'http://ww' . $zone . '.sinaimg.cn/' . $type . '/' . $pid;
        return $url;
    }

    /**
     * 新浪微博登录(无加密接口版本)
     * @param  string $u 用户名
     * @param  string $p 密码
     * @return string    返回最有用最精简的cookie
     */
    public static function login($u, $p) {
        $loginUrl = 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=1403138799543';
        $loginData['entry'] = 'sso';
        $loginData['gateway'] = '1';
        $loginData['from'] = 'null';
        $loginData['savestate'] = '30';
        $loginData['useticket'] = '0';
        $loginData['pagerefer'] = '';
        $loginData['vsnf'] = '1';
        $loginData['su'] = base64_encode($u);
        $loginData['service'] = 'sso';
        $loginData['sp'] = $p;
        $loginData['sr'] = '1920*1080';
        $loginData['encoding'] = 'UTF-8';
        $loginData['cdult'] = '3';
        $loginData['domain'] = 'sina.com.cn';
        $loginData['prelt'] = '0';
        $loginData['returntype'] = 'TEXT';
        return self::loginPost($loginUrl, $loginData);
    }

    /**
     * 发送微博登录请求
     * @param  string $url  接口地址
     * @param  array  $data 数据
     * @return json         算了，还是返回cookie吧//返回登录成功后的用户信息json
     */
    private static function loginPost($url, $data) {
        $tmp = '';
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $tmp .= $key . "=" . $value . "&";
            }
            $post = trim($tmp, "&");
        } else {
            $post = $data;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $return = curl_exec($ch);
        curl_close($ch);
        return 'SUB' . self::getSubstr($return, "Set-Cookie: SUB", '; ') . ';';
    }

    private static function getSubstr($str, $leftStr, $rightStr) {
        $left = strpos($str, $leftStr);
        //echo '左边:'.$left;
        $right = strpos($str, $rightStr, $left);
        //echo '<br>右边:'.$right;
        if ($left <= 0 or $right < $left) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }

}
